import { useEffect } from "react";
import { message, Space, Form, Input, Popconfirm, Avatar } from "antd";
import { Button, Card as SemiCard, ButtonGroup, List } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete, IconEdit } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import localforage from "localforage";
import { validate as uuidValidate } from "uuid";

const GatewayCard = ({ cardBodyHeight, handleSelectedGateway }) => {
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent, setModalStyle } = useModel("global.modal");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
        gateways: [],
        selectedGateway: null,
        pageSize: 20,
        page: 1,
    });

    const loadGateways = async () => {
        state.loading = true;
        try {
            let gateways = await localforage.getItem("myManagedGateways-" + baseInfo.uuid);
            if (gateways && gateways.length) {
                state.gateways = gateways;
                state.selectedGateway = gateways[0];
                handleSelectedGateway(gateways[0]);
            }
        } catch (err) {}
        state.loading = false;
    };

    useEffect(() => {
        loadGateways();
    }, [baseInfo.uuid]);

    const openAddGatewayModal = async () => {
        setModalTitle("添加组织网关并申请成为管理员");
        setModalVisible(true);
        setModalWidth(650);
        setModalStyle({ top: 100 });
        setModalComponent(<AddGateway gateways={state.gateways} reloadData={loadGateways} />);
    };

    const openSetRemark = (item) => {
        setModalTitle("设置网关备注");
        setModalVisible(true);
        setModalStyle({ top: 100 });
        setModalComponent(<SetRemark currGateway={item} gateways={state.gateways} reloadData={loadGateways} />);
    };

    const deleteGateway = async (currGateway) => {
        let index = state.gateways.findIndex((item) => item.url === currGateway.url);
        if (index !== -1) {
            state.gateways.splice(index, 1);
            try {
                await localforage.setItem("myManagedGateways-" + baseInfo.uuid, [...state.gateways]);
                loadGateways();
                message.success("成功删除本地组织网关信息");
            } catch (err) {}
        }
    };

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>网关列表</span>}
            headerExtraContent={
                <ButtonGroup>
                    <Button icon={<IconPlusCircle onClick={openAddGatewayModal} />}></Button>
                    <Button icon={<IconRefresh onClick={loadGateways} />}></Button>
                </ButtonGroup>
            }
            headerStyle={{ padding: "10px 14px" }}
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 1, height: cardBodyHeight - 2, overflow: "auto" }}
        >
            <List
                loading={state.loading}
                dataSource={state.gateways}
                renderItem={(item, index) => (
                    <List.Item
                        key={index}
                        className={`list-item ${state.selectedGateway?.url === item?.url ? "list-selected-item" : ""}`}
                        style={{ padding: "12px 12px 12px 24px" }}
                        main={
                            <div>
                                <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.title || "-"}</div>
                                {item?.url}
                            </div>
                        }
                        extra={
                            <ButtonGroup theme="borderless">
                                <Button icon={<IconEdit />} onClick={() => openSetRemark(item)} />
                                <Popconfirm title="确认要移除该组织网关的信息?" onConfirm={() => deleteGateway(item)}>
                                    <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                                </Popconfirm>
                            </ButtonGroup>
                        }
                        onClick={() => {
                            state.selectedGateway = item;
                            handleSelectedGateway(item);
                        }}
                    ></List.Item>
                )}
            />
        </SemiCard>
    );
};

const AddGateway = ({ gateways, reloadData }) => {
    const { remoteData, runEnv } = useModel("global");
    const { baseInfo } = useModel("person.info");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const onFinish = async (values) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            p2pNodeUuid: values.gatewayUuid,
            serviceUrl: values.gatewayUrl,
            serviceName: "/api/v1/administrator/apply",
            params: {
                personUuid: baseInfo.uuid,
                realName: baseInfo.realName,
                runEnv,
            },
        });
        if (res !== null) {
            let data = JSON.parse(JSON.stringify(gateways));
            if (data.findIndex((item) => item.url === values.gatewayUrl && item.gatewayUuid === values.gatewayUuid) === -1) {
                data.push({ uuid: values.gatewayUuid, url: values.gatewayUrl, title: "" });
            }
            try {
                await localforage.setItem("myManagedGateways-" + baseInfo.uuid, data);
                reloadData();
                message.success("成功申请网关管理员");
                onCloseGlobalModal();
            } catch (err) {}
        }
    };

    const gatewayUrlValidater = (rule, value) => {
        if (value && validates.isURL(value)) {
            return Promise.resolve();
        } else {
            return Promise.reject("请输入正确的网关地址，示例: http://127.0.0.1:9999");
        }
    };

    const gatewayUuidValidator = async (rule, value) => {
        if (value && uuidValidate(value)) {
            return Promise.resolve();
        } else {
            return Promise.reject("请输入正确的网关UUID");
        }
    };

    return (
        <Form form={form} onFinish={onFinish} labelCol={{ span: 5 }} style={{ marginTop: 20 }}>
            <Form.Item
                label="组织网关地址"
                name="gatewayUrl"
                // help={"示例: http://127.0.0.1:9999 或 http://www.sample.com:9999"}
                rules={[{ required: true, validator: gatewayUrlValidater }]}
            >
                <Input placeholder="请输入" />
            </Form.Item>

            <Form.Item label="网关UUID" name="gatewayUuid" validateTrigger="onBlur" rules={[{ required: true, validator: gatewayUuidValidator }]}>
                <Input placeholder="请输入" />
            </Form.Item>

            <div style={{ textAlign: "center" }}>
                <Button type="primary" htmlType="submit">
                    管理员申请
                </Button>
            </div>
        </Form>
    );
};

const SetRemark = ({ currGateway, gateways, reloadData }) => {
    const { baseInfo } = useModel("person.info");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        remark: "",
    });

    const onChangeRemark = (e) => (state.remark = e.target.value);

    const saveRemark = async () => {
        if (!state.remark) return message.warning("请输入备注信息");
        let data = [...gateways];
        let index = data.findIndex((item) => item.url === currGateway.url);
        if (index !== -1) {
            data[index] = Object.assign({}, data[index], { title: state.remark });
            try {
                await localforage.setItem("myManagedGateways-" + baseInfo.uuid, data);
                reloadData();
                message.success("成功申请网关管理员");
                onCloseGlobalModal();
            } catch (err) {}
        }
    };

    useEffect(() => {
        let index = gateways.findIndex((item) => item.url === currGateway);
        if (index !== -1) {
            state.remark = gateways[index].title;
        }
    }, []);

    return (
        <Space direction="vertical" size={20} style={{ width: "100%", padding: "0 20px" }}>
            <Form.Item label="网关备注">
                <Input placeholder="输入组织网关备注" value={state.remark} onChange={onChangeRemark} />
            </Form.Item>
            <div style={{ textAlign: "center" }}>
                <Button type="primary" onClick={saveRemark}>
                    保存
                </Button>
            </div>
        </Space>
    );
};

export default GatewayCard;
